$(function () {
    let queryUrl = '../sparepartin/list';
    let id = getQueryString('Id');
    if(id){
        queryUrl += '?id=' + id;
    }
    $("#jqGrid").Grid({
        url: queryUrl,
        colModel: [
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
            {label: '入库单号', name: 'inCode', index: 'IN_CODE', width: 130},
            {label: '备件编码', name: 'partCode', index: 'PART_CODE', width: 80},
            {label: 'ERP编码', name: 'erpCode', index: 'ERP_CODE', width: 80},
            {label: '备件名称', name: 'name', index: 'NAME', width: 80},
            {label: '规格', name: 'spec', index: 'SPEC', width: 120},
            {label: '入库仓库', name: 'intStore', index: 'SH.NAME', width: 120},
            {label: '货位', name: 'cargoLocation', index: 'CARGO_LOCATION', width: 80},
            {
                label: '入库日期', name: 'inDate', index: 'IN_DATE', width: 80, formatter: function (value) {
                    return transDate(value, 'yyyy-MM-dd');
                }
            },
            {label: '入库数量', name: 'inNum', index: 'IN_NUM', width: 60},
            {label: '单价', name: 'partPrice', index: 'PART_PRICE', width: 60},
            {label: '单位', name: 'partUnit', index: 'PART_UNIT',   width: 45},
            {label: '使用单位', name: 'unit', index: 'USE_UNIT', hidden: true},
            {
                label: '添加时间', name: 'createDate', index: 'CREATE_DATE', width: 80, formatter: function (value) {
                    return transDate(value, 'yyyy-MM-dd');
                }
            },
            {
                label: '来源', name: 'resources', index: 'RESOURCES', width: 60, formatter: function (value) {
                    var res= sysEnums.SPARE_RESOURCES_TYPE[value];
                    if(!res){
                        res="未知";
                    }
                    return res;
                }
            },
            {label: '计划编码', name: 'businessCode', sortable: false, width: 80},
            {label: '供应商', name: 'supplierName', sortable: false, width: 80},
            {label: '入库人员', name: 'stockKeeper', sortable: false, width: 60},
            {label: '备注', name: 'remark', sortable: false, width: 80},
            {
                label: 'ERP关联', name: 'erpInboundRecordId', index: 'ERP_INBOUND_RECORD_ID', width: 120, sortable: false,
                formatter: function (value, col, row) {
                    if(value){
                        return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.shviewOption(\"" + escape(JSON.stringify(row)) + "\")'>"+value+"</button>";
                    }else{
                        return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.shviewOption(\"" + escape(JSON.stringify(row)) + "\")'>&nbsp;关联</button>";
                    }
                }
            },
        ]
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        cargoLocation:true,
        cargoLocationName:false,
        title: null,
        sparePartIn: {
            createUser: '',
            createDate: '',
            checkDate: '',
            checkStatus: '',
            checkUser: '',
            updateDate: '',
            updateUser: '',
            delFlag: '',
            remark: '',
            operationName: '',
            operation: '',
            procUse: '',
            useDevId: '',
            useDevName: '',
            useDevCode: '',
            inNum: '',
            partPrice: '',
            partUnit: '',
            spec: '',
            name: '',
            partCode: '',
            cargoLocation: '',
            inStoreId: '',
            intStore: '',
            useUnit: '',
            inDate: '',
            inCode: '',
            resources: '',
            id: '',
            stockKeeper:'',
            supplierName:'',
        },
        newOldName:'',
        workShopName:'',
        isWorkShopName:false,
        workShopPosition:'',
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ],
            inNum: [
                {
                    validator: (rule, value, callback) => {
                        if (!value) {
                            callback(new Error('入库数量不能为空！'));
                        }else {
                            callback();
                        }
                    },
                    trigger: 'blur',
                }
            ],
            partCode: [
                {required: true, message: '系统编码不能为空', trigger: 'change'}
            ],
            supplierName:[
                {required: true, message: '供应商不能为空', trigger: 'blur'}
            ],
            inStoreId: [
                {required: true, message: '入库仓库必选！', trigger: 'change'}
            ],
            stockKeeper:[
                {required:true,message:'入库人员不能为空！',trigger:'blur'}
            ]
        },
        q: {
            useUnit:'', // 使用单位
            partName: '', // 备件名称
            spec: '', // 备件规格
            producor:'', // 供应厂家
            beginTime:'', // 开始时间
            endTime:'' ,// 结束时间
            resources:'',//来源
            erpCode:''//erp编码
        },
        //货位ID，如果货位ID为空，则后台自动添加数据保存
        hwID:'',
        optionList:'',//货位列表，实时查询
        newOldWorkShop:[
            {
                name:'YBG',
                id:'YBG'
            },
            {
                name:'NBG',
                id:'NBG'
            }
        ],
        storeId:'', //仓库ID
        storeName:'',//仓库名字
        flag:'', //是否新增库位判断标识
        sourceList: enumsToList('SPARE_RESOURCES_TYPE'),
        transitNum: 0, // 关联需求计划详情，展示用
        planItemDesc: '', // 关联需求计划明细描述 格式：
        partPrice: '', // 入库备件价格
        isDisabled: false, // 控制入库按钮
        useUnitList:[] ,// 使用单位列表
        associateRecord:{
            erpRecord:''
        },
        dataTime:[],//时间范围框绑定
    },
    created: function () {
        this.loadWorshopList();
    },
    methods: {
        /*车间失去焦点*/
        inputBlur(e){
            Ajax.request({
                url: '../sys/dept/validCjCode',
                params: {cjCode:e.target.value},
                type: 'POST',
                successCallback: function (res) {
                    if(res.code==0){
                       vm.isWorkShopName = true
                    }
                }
            });
        },
        /*打开关联ERP记录*/
        shviewOption:function (res) {
            let data = JSON.parse(unescape(res))
            if(data.resources != '4'){
                layer.alert('只有来源为需求计划的工单可以关联ERP！', {icon: 7});
                return
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 请从以下事务中关联ERP',
                content: '../spare/sparePartErpCodeSelect.html?id='+data.id,
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getSparePart();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        Ajax.request({
                            url: '../sparepartin/associateErpInboundRecord',
                            params: {id:data.id,erpTransationId:res.transactionId},
                            type: 'POST',
                            successCallback: function (res) {
                                vm.reload();
                            }
                        });
                        layer.close(index);
                    }
                }
            })

        },
        recordAreAssociated: function () {

        },
        loadWorshopList:function (){
            var _this = this;
            Ajax.request({
                url: '../sys/dept/listByDeptLevel?deptLevel=2',
                async: true,
                successCallback: data=> {
                    this.useUnitList = data.list;
                }
            });
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.storeName = '';
            vm.planItemDesc = '';
            vm.transitNum = '';
            vm.sparePartIn = {
                remark: '',
                operationName: '',
                operation: '',
                procUse: '',
                useDevId: '',
                useDevName: '',
                useDevCode: '',
                inNum: 1,
                partPrice: '',
                partUnit: '',
                spec: '',
                name: '',
                partCode: '',
                cargoLocation: '',
                cargoLocationName: '',
                inStoreId: '',
                intStore: '',
                useUnit: '',
                inDate: '',
                inCode: '',
                resources: '',
                id: '',
                supplierName:'',
                stockKeeper:'',
                partNeedsItemId: '' // 关联备件需求计划详情ID
            };
            vm.showLoc(1);
            vm.flag=0;

        },
        saveOrUpdate: function (event) {
            var url = vm.sparePartIn.id == (null || '') ? "../sparepartin/save" : "../sparepartin/update";

            var cargoLocationName = vm.sparePartIn.cargoLocationName;
            if(vm.flag==1){
                // 手动输入库位
                vm.sparePartIn.cargoLocation="";
                if(cargoLocationName.length==0){
                    alert("备件存放位置不能为空！");
                    return;
                }else{
                    //判断是否存在当前库位
                    var storeId = vm.sparePartIn.inStoreId;
                    var spareCode = vm.sparePartIn.partCode;
                    var postion = vm.sparePartIn.cargoLocationName;
                    Ajax.request({
                        url: "../sparestorepos/queryIsHave",
                        params: {"storeId": storeId,"spareCode":spareCode,'postion':postion},
                        async: false,
                        successCallback: function (r) {
                            var result = r.isHave;
                            if(result==1){
                                alert("备件存放位置已经存在！");
                                return ;
                            }
                        }
                    });
                }
            }else if(vm.flag == 0){
                // 手动选择现有库位
                if(!vm.sparePartIn.cargoLocation){
                    alert("货位必选！");
                    return;
                }
            }

            // 校验来源
            if(vm.sparePartIn.resources == 4) {
                // 关联计划必填
                if(!vm.sparePartIn.partNeedsItemId){
                    iview.Message.error("备件来源为[需求计划]时，关联计划必选！");
                    return;
                }
                // 入库数量不得大于需求在途数 校验
                let transitNumIn = parseInt(vm.transitNum);
                let inNum = parseInt(vm.sparePartIn.inNum);
                if(transitNumIn < inNum){
                    iview.Message.error("入库数量不得大于需求在途数！");
                    return;
                }
            }
            // 禁用提交按钮，防止重复提交
            if(vm.isDisabled){
                iview.Message.error("备件入库处理中，请勿重复点击！");
                return;
            }
            this.$Loading.start();
            vm.isDisabled = true;
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.sparePartIn),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    vm.isDisabled = false;
                    vm.$Loading.finish();
                    vm.newOldName = '';
                    vm.workShopPosition = '';
                    vm.workShopName = '';
                    vm.isWorkShopName = false;
                    vm.reload();
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../sparepartin/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../sparepartin/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.sparePartIn = r.sparePartIn;
                }
            });
        },
        dataChange:function (e) {
         if(e.length>0){
            vm.q.beginTime = e[0];
             vm.q.endTime = e[0]
         }else{
             vm.q.beginTime = '';
             vm.q.endTime ='';
         }
        },
        reload: function (event) {
            vm.showList = true;
            let param = {};
            if(vm.q.useUnit){
                param.useUnit = vm.q.useUnit;
            }
            if(vm.q.partName){
                param.partName = vm.q.partName;
            }
            if(vm.q.spec){
                param.spec = vm.q.spec;
            }
            if(vm.q.erpCode){
                param.erpCode = vm.q.erpCode;
            }
            if(vm.q.producor){
                param.producor = vm.q.producor;
            }
            if(vm.q.beginTime){
                param.beginTime = gmt2DateStr(vm.q.beginTime);
            }
            if(vm.q.endTime){
                param.endTime = gmt2DateStr(vm.q.endTime);
            }
            if(vm.q.resources){
                param.resources = vm.q.resources;
            }
            // 清空postData缓存数据
            var postData = $("#jqGrid").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            // 获取当前分页信息
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: param,
                page: page
            }).trigger("reloadGrid");
        },
        getStorePos: function () {
            // var storeId =
            Ajax.request({
                url: "../sparestorepos/queryAll",
                params: {"storeId": vm.sparePartIn.inStoreId ,"partCode":vm.sparePartIn.partCode},
                async: true,
                successCallback: function (r) {
                    vm.optionList = r.list;
                }
            });
        },
        reloadSearch: function () {
            vm.q = {
                useUnit:'', // 使用单位
                partName: '', // 备件名称
                spec: '', // 备件规格
                producor:'', // 供应厂家
                beginTime:'', // 开始时间
                endTime:'' ,// 结束时间,
                resources:'',//来源
                erpCode:''
            };
            vm.dataTime = [];
            vm.reload();
        },
        handleSubmit: function (name) {
            if(vm.flag==1){
               if(!vm.newOldName){
                   layer.alert('请选择新老车间！', {icon: 7});
                   return
               }
               if(!vm.workShopPosition){
                   layer.alert('请输入库位！', {icon: 7});
                   return
               }
               if(vm.sparePartIn.resources !='4'){
                   if(!vm.isWorkShopName){
                       layer.alert('车间代码验证不正确，请重新输入！', {icon: 7});
                       return
                   }
               }
            }
            vm.sparePartIn.cargoLocationName = vm.newOldName+'-'+vm.workShopName+'-'+vm.workShopPosition
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            vm.newOldName = '';
            vm.workShopPosition = '';
            vm.workShopName = '';
            vm.isWorkShopName = false;
            handleResetForm(this, name);
        },

        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        handleBeforeUpload: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleSuccess: function (res, file) {
            if (!res.err) {
                this.$Loading.finish();
                alert('导入成功', function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.msg
                })
            }
        },
        handleError: function (err, file) {
            alert('导入失败');
        },
        exportData: function () {
            exportFile('#rrapp', '../sparepartin/export', {'name': vm.q.name});
        },
        //显示设备列表-使用设备码
        getDeviceInfo: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择设备',
                content: '../sys/deviceInfoSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getDeviceInfo();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.sparePartIn.useDevCode = res.devCode;
                        vm.sparePartIn.useDevName = res.devName;
                    }
                }
            })
        },
        getSparePart: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择备件',
                content: '../spare/sparePartSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getSparePart();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.storeName = '';
                        vm.transitNum = 0;
                        vm.planItemDesc = '';
                        vm.partPrice = '';

                        vm.sparePart = res;
                        vm.sparePartIn.partCode = vm.sparePart.partCode;
                        vm.sparePartIn.name = vm.sparePart.name;
                        vm.sparePartIn.spec = vm.sparePart.spec;
                        vm.sparePartIn.partPrice = vm.sparePart.price;
                        vm.sparePartIn.unit = vm.sparePart.unit;
                        vm.sparePartIn.partUnit = vm.sparePart.useUnit;
                    }
                }
            })
        },
        relateNeedsPlanDetail: function () {
            if(!vm.sparePartIn.partCode){
                iview.Message.error("请先选择入库备件！");
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择备件需求计划明细',
                content: '../spare/sparePartNeedsPlanDetailRelate.html?sparePartCode=' + vm.sparePartIn.partCode,
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getSparePart();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.workShopName = res.cjCode;
                        vm.planItemDesc = res.businessCode + ' ' + res.materialName + ' ' + res.spec;
                        vm.sparePartIn.partNeedsItemId = res.id;
                        vm.transitNum = res.transitNum;
                        vm.partPrice = res.planPrice;
                        // 特殊备件
                        if(res.remark == '1' || res.remark == '0'){
                            iview.Message.warning({
                                content: '入库完毕后请告知备件管理员该备件[' + vm.planItemDesc + ']已入库！',
                                duration: 10,
                                closable: true
                            });
                        }
                    }
                }
            })
        },
        //选择入库仓库
        getStoreHouse: function () {
            if(vm.sparePartIn.partCode==""|| vm.sparePartIn.partCode==null){
                alert("请先选择入库的备件，在选择仓库");
                return;
            }else {
                openWindow({
                    type: 2,
                    title: '<i class="fa fa-institution"></i> 选择仓库',
                    content: '../sys/storeHouseSelect.html?type=1',
                    btn: ['确定', '取消'],
                    btn1: function (index) {
                        var iframeWin = window["layui-layer-iframe" + index];
                        var res = iframeWin.getStoreHouse();
                        if (!res) {
                            iview.Message.error("请选择一条记录");
                        } else {
                            layer.close(index);
                            vm.sparePartIn.intStore = res.storeCode;
                            vm.sparePartIn.inStoreId = res.id;
                            vm.storeName = res.name;
                            //获取位置列表
                            vm.getStorePos();
                        }
                    }
                })
            }
        },
        showLoc:function (type) {
            if(type==0){
                // 手动输入库位
                vm.cargoLocation = false;
                vm.cargoLocationName= true;
                vm.sparePartIn.cargoLocationName="待验架";
                vm.flag = 1;
                vm.newOldName = '';
                if(vm.sparePartIn.resources !='4'){
                   vm.workShopName = ''
                }
                vm.isWorkShopName = false;
                vm.workShopPosition = '';
            }else if(type==1){
                // 从现有库位中选择
                vm.cargoLocation = true;
                vm.cargoLocationName= false;
                vm.sparePartIn.cargoLocation="";
                vm.flag =0;
                vm.newOldName = '';
                if(vm.sparePartIn.resources !='4'){
                    vm.workShopName = ''
                }
                vm.isWorkShopName = false;
                vm.workShopPosition = '';
            }
        }
    }
});
